package com.zdy.gaoji;

import com.sun.media.jfxmedia.events.PlayerEvent;

import javax.swing.text.PlainDocument;

/**
 * Created by 逸足天涯
 * on 3/10/2020.
 */

//测试生产者消费者2。信号灯法，用标志位解决
public class TestPc2 {
    public static void main(String[] args) {
        Tv tv = new Tv();
        new Palyer(tv).start();
        new Watcher(tv).start();
    }

}

//生产者演员
class Palyer extends Thread{
    Tv tv;
    Palyer(Tv tv){
        this.tv = tv;
    }

    @Override
    public void run() {
        for (int i = 0; i < 20; i++) {
            if(i%2 == 0){
                this.tv.play("快乐大本营正在播放");
            }else{
                this.tv.play("抖音记录美好生活");
            }
        }
    }
}


//消费者
class Watcher extends Thread{
    Tv tv;
    Watcher(Tv tv){
        this.tv = tv;
    }

    @Override
    public void run() {
        for (int i = 0; i < 20; i++) {
            tv.watch();
        }
    }
}
class Tv{
    //演员表演观众等待
    //观众观看演员等待
    String vioce;
    boolean flag = true;

    //表演
    public synchronized void play(String vioce){
        if (!flag){
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        System.out.println("演员表演了" + vioce);
        this.notifyAll();//通知唤醒
        this.vioce = vioce;
        this.flag = !this.flag;
    }

    public synchronized void watch(){
        System.out.println("观众观看");
        if (flag){
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        System.out.println("观看了"+ vioce);
        this.notifyAll();
        this.flag = !this.flag;
    }
}
